package com.derbysoft.nuke.kafka.manager.integration.kafka;

import com.google.common.collect.Lists;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class KafkaConsumerStarter2 {

    String bootstrapServers = "localhost:9091;localhost:9092;localhost:9093";

    public void start() {
        Map<String, Object> conf = new HashMap<>();
        conf.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        conf.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        conf.put(ConsumerConfig.GROUP_ID_CONFIG, "consumer-group-check");
        conf.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        conf.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());

        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(conf);

//        List<TopicPartition> partitions = new ArrayList<>();
//        kafkaConsumer.partitionsFor("__consumer_offsets").forEach(partitionInfo -> {
//            partitions.add(new TopicPartition(partitionInfo.topic(), partitionInfo.partition()));
//        });

        kafkaConsumer.subscribe(Lists.newArrayList("__consumer_offsets"));
//        kafkaConsumer.seekToBeginning(partitions);
        while (true) {
            ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(1000);
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                System.out.println(String.format("message of topic[%s], partition[%s], offset[%s], content[%s]", consumerRecord.topic(), consumerRecord.partition(), consumerRecord.offset(), consumerRecord.value()));
            }
            try {
                TimeUnit.MILLISECONDS.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        KafkaConsumerStarter2 starter = new KafkaConsumerStarter2();
        starter.start();
    }

}
